package com.wxd.framework.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wxd.framework.dao.MenuDao;
import com.wxd.framework.dao.RoleMenuDao;
import com.wxd.framework.dao.UserDao;
import com.wxd.framework.entity.Menu;
import com.wxd.framework.entity.RoleMenu;
import com.wxd.framework.entity.User;
import com.wxd.framework.service.FrameService;
import com.wxd.framework.vo.TreeItem;

@Service
public class FrameServiceImpl extends BaseServiceImpl implements FrameService {
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private MenuDao menuDao;
	@Autowired
	private RoleMenuDao roleMenuDao;
	
	/* (non-Javadoc)
	 * @see com.wxd.framework.service.FrameService#loginValidate(java.lang.String, java.lang.String)
	 */
	@Override
	public User loginValidate(String userName, String password) {
		User user = new User();
		List<User> list = userDao.selectByUserName(userName);
		if (list == null || list.size() == 0) {
			user.setMessage("用户名不存在");
		}else if (list.size() > 1) {
			user.setMessage("用户名异常（重复）");
		}else {
			user = list.get(0);
			if (user.getIsStoped()) {
				user.setMessage("该用户已停用");
			}else if (!password.equals(user.getUserPassword())) {
				user.setMessage("密码错误");
			}
		}
		return user;
	}

	/* (non-Javadoc)
	 * @see com.wxd.framework.service.FrameService#getSysMenuItemsByParentId(java.lang.String, java.lang.String)
	 */
	@Override
	public List<TreeItem> getSysMenuItemsByParentId(String parentId, String userId) {
		List<TreeItem> tree = new ArrayList<>();
		List<Menu> menus = menuDao.selectByParentId(parentId);
		List<RoleMenu> roleMenus = roleMenuDao.selectDistMenuIdByUserId(userId);
		for(Menu menu : menus){
			TreeItem item = new TreeItem(menu);
			for(RoleMenu roleMenu : roleMenus){
				if (roleMenu.getMenuId().equals(item.getId())) {
					tree.add(item);
					break;
				}
			}
		}		
		return tree;
	}

	/* (non-Javadoc)
	 * @see com.wxd.framework.service.FrameService#resetPassword(java.lang.String, java.lang.String)
	 */
	@Override
	public void resetPassword(String userId, String password) {
		User user = new User();
		user.setId(userId);
		user.setUserPassword(password);
		userDao.updateSelective(user);
	}

}
